﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Collections.Generic;

namespace ThienLoc.Admin
{
    public class PrepareDataForTreeView
    {
        public void PopulateRootLevel(TreeView trvDonVi)
        {
            string sql = "SELECT ID,Ten,(select count(*) FROM dbo.tblT2BMenu WHERE ParentID=M.ID) childnodecount FROM dbo.tblT2BMenu M WHERE M.ParentID IS NULL";
            DataTable tblRootNode = SqlHelper.ExecuteDataTable(CommandType.Text, sql);
            PopulateNodes(tblRootNode, trvDonVi.Nodes);
        }

        public void PopulateSubLevel(int FatherID, TreeNode parentNode)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@FatherID", SqlDbType.Int, ParameterDirection.Input, FatherID));
            string sql = "SELECT ID,Ten,(SELECT COUNT(*) FROM dbo.tblT2BMenu WHERE ParentID=M.ID) childnodecount FROM dbo.tblT2BMenu M WHERE M.ParentID != M.ID";
            DataTable tblSubNode = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParams);
            PopulateNodes(tblSubNode, parentNode.ChildNodes);
        }

        public void PopulateNodes(DataTable tblNode, TreeNodeCollection arrNodes)
        {
            foreach (DataRow dr in tblNode.Rows)
            {
                TreeNode tn = new TreeNode();
                tn.Text = dr["Ten"].ToString();
                tn.Value = dr["ID"].ToString();
                arrNodes.Add(tn);
                tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0);
            }
        }
    }
}
